const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}


function dateTime() {
  let date = new Date();
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return year + "-" + month + "-" + day;
}


const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

const apiHttp = "https://hmjy.hmjync.com/brest/";
const imgHttp = "https://hmjy.hmjync.com/filesystem/";
const ERR_OK = '000000';

function getHeader() {
  var t = wx.getStorageSync('token');
  return { Authorization: t }
}

function fun(url, method, data) {
  data = data || {};
  return new Promise((resolve, reject) => {
    wx.request({
      url: apiHttp + url,
      data: data,
      method: method,
      header: getHeader(),
      success: function (res) {
        if (res.data.return_code == ERR_OK) {
          resolve(res.data.return_data)
        } else if (res.data.return_code == "401") {
          wx.showToast({
            title: '授权信息过期,请重新登录',
            duration: 2000,
            icon: 'none',
            success: function (res) {
              wx.reLaunch({
                url: '/pages/login/login'
              })
            },
          })
        } else {
          reject(res)
        }
      },
      error: function (res) {
        let msg = {
          return_msg: '网络异常'
        }
        reject(msg);
      },
    })
  })
}


module.exports = {
  formatTime,
  apiHttp: apiHttp,
  imgHttp: imgHttp,
  "get": function (url, data) {
    return fun(url, "get", data);
  },
  "post": function (url, data) {
    return fun(url, "post", data);
  },
  "dateTime": function () {
    return dateTime();
  }
}
